#!/usr/bin/env python3
"""
LangGraph FastAPI Demo 快速启动脚本
"""

import subprocess
import sys
import os
import time
import requests

def check_dependencies():
    """检查依赖是否已安装"""
    try:
        import fastapi
        import uvicorn
        import pydantic
        import dotenv
        print("✅ 所有依赖已安装")
        return True
    except ImportError as e:
        print(f"❌ 缺少依赖: {e}")
        print("请运行: pip install -r requirements.txt")
        return False

def start_server():
    """启动服务器"""
    print("🚀 启动 LangGraph FastAPI Demo 服务器...")
    
    # 检查配置文件
    if not os.path.exists(".env"):
        if os.path.exists("config.env"):
            print("📝 复制配置文件...")
            import shutil
            shutil.copy("config.env", ".env")
        else:
            print("⚠️  未找到配置文件，使用默认配置")
    
    # 启动服务器
    try:
        subprocess.run([sys.executable, "main.py"], check=True)
    except KeyboardInterrupt:
        print("\n👋 服务器已停止")
    except Exception as e:
        print(f"❌ 启动失败: {e}")

def test_endpoints():
    """测试API端点"""
    print("🧪 测试API端点...")
    
    base_url = "http://localhost:8000"
    endpoints = [
        "/",
        "/health",
        "/basic-graph",
        "/conditional-graph",
        "/parallel-graph",
        "/state-management",
        "/tool-calling",
        "/loop-graph",
        "/error-handling"
    ]
    
    for endpoint in endpoints:
        try:
            if endpoint in ["/", "/health"]:
                response = requests.get(f"{base_url}{endpoint}")
            else:
                response = requests.post(f"{base_url}{endpoint}", 
                                       json={"input_data": {"message": "测试消息"}})
            
            if response.status_code == 200:
                print(f"✅ {endpoint} - 正常")
            else:
                print(f"❌ {endpoint} - 状态码: {response.status_code}")
        except requests.exceptions.ConnectionError:
            print(f"❌ {endpoint} - 连接失败")
        except Exception as e:
            print(f"❌ {endpoint} - 错误: {e}")

def main():
    """主函数"""
    print("=" * 50)
    print("🚀 LangGraph FastAPI Demo 启动器")
    print("=" * 50)
    
    # 检查依赖
    if not check_dependencies():
        return
    
    # 显示选项
    print("\n请选择操作:")
    print("1. 启动服务器")
    print("2. 测试API端点")
    print("3. 启动服务器并测试")
    print("4. 退出")
    
    choice = input("\n请输入选项 (1-4): ").strip()
    
    if choice == "1":
        start_server()
    elif choice == "2":
        test_endpoints()
    elif choice == "3":
        print("启动服务器...")
        # 这里可以添加后台启动服务器的逻辑
        print("请手动启动服务器: python main.py")
        print("然后在另一个终端运行: python test_api.py")
    elif choice == "4":
        print("👋 再见!")
    else:
        print("❌ 无效选项")

if __name__ == "__main__":
    main()
